import 'package:flutter/material.dart';
import '../../core/app_theme.dart';
import '../../widgets/product_card.dart';
import '../../models/product_model.dart';
import '../../route/router.dart';

// 在HomePage类中添加以下代码
import 'dart:async';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 添加PageController和当前页码
  final PageController _pageController = PageController(initialPage: 0);
  int _currentPage = 0;
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    // 初始化自动滚动计时器
    _timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      // 添加mounted检查，确保页面未被销毁
      if (mounted) {
        _currentPage = (_currentPage + 1) % 3;
        _pageController.animateToPage(
          _currentPage,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
        );
      } else {
        // 如果页面已被销毁，取消定时器
        timer.cancel();
      }
    });
  }

  @override
  void dispose() {
    _timer.cancel(); // 取消计时器
    _pageController.dispose(); // 释放PageController
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('首页'),
        actions: [IconButton(icon: const Icon(Icons.search), onPressed: () {})],
      ),
      body: ListView(
        children: [
          // 轮播图
          _buildBanner(),
          // 分类入口
          _buildCategoryGrid(),
          // 商品列表
          _buildProductList(),
        ],
      ),
    );
  }

  Widget _buildBanner() {
    return SizedBox(
      height: 180,
      child: Stack(
        children: [
          PageView.builder(
            controller: _pageController,
            itemCount: 3,
            onPageChanged: (int page) {
              setState(() {
                _currentPage = page;
              });
            },
            itemBuilder: (context, index) {
              // 图片链接列表
              const imageUrls = [
                'https://ts2.tc.mm.bing.net/th/id/OIP-C.MtG5BHWcXTADVW7trlPvpAHaEJ?cb=thfvnext&rs=1&pid=ImgDetMain&o=7&rm=3',
                'https://ts1.tc.mm.bing.net/th/id/R-C.0865f847a0dbf540fe98f1a60d5365de?rik=49%2fKrjrERWGnPA&riu=http%3a%2f%2fpic3.bbzhi.com%2fxitongbizhi%2fkuanpingcgshejibizhi1%2fcomputer_kuan_183504_10.jpg&ehk=q%2byEsvraxNLNJ6mgrhv7fnqtIt6PuyntaAx9%2fA0iVSI%3d&risl=&pid=ImgRaw&r=0',
                'https://ts2.tc.mm.bing.net/th/id/OIP-C.nj1LSkxzNhWo8xjH2WNH-wHaEK?cb=thfvnext&rs=1&pid=ImgDetMain&o=7&rm=3',
              ];

              return Container(
                margin: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: AppTheme.primaryLight.withOpacity(0.5),
                ),
                child: Image.network(
                  imageUrls[index],
                  fit: BoxFit.cover,
                  width: double.infinity,
                  height: double.infinity,
                  errorBuilder: (_, __, ___) => Center(
                    child: Text(
                      '图片加载失败',
                      style: const TextStyle(fontSize: 16, color: Colors.white),
                    ),
                  ),
                ),
              );
            },
          ),
          // 添加下标指示器
          Positioned(
            bottom: 10,
            left: 0,
            right: 0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: List.generate(3, (index) {
                return Container(
                  width: 8,
                  height: 8,
                  margin: const EdgeInsets.symmetric(horizontal: 4),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: _currentPage == index
                        ? Colors.white
                        : Colors.white.withOpacity(0.5),
                  ),
                );
              }),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCategoryGrid() {
    const categories = [
      {'icon': Icons.phone_android, 'name': '手机'},
      {'icon': Icons.computer, 'name': '电脑'},
      {'icon': Icons.headset, 'name': '耳机'},
      {'icon': Icons.watch, 'name': '手表'},
      {'icon': Icons.tv, 'name': '电视'},
      {'icon': Icons.more, 'name': '更多'},
    ];

    return GridView.count(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      crossAxisCount: 3,
      children: categories.map((category) {
        return InkWell(
          onTap: () {},
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                category['icon'] as IconData,
                size: 30,
                color: AppTheme.primaryColor,
              ),
              const SizedBox(height: 8),
              Text(category['name'] as String),
            ],
          ),
        );
      }).toList(),
    );
  }

  Widget _buildProductList() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Padding(
          padding: EdgeInsets.all(8.0),
          child: Text(
            '热门推荐',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
        ),
        GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 0.7,
            crossAxisSpacing: 8,
            mainAxisSpacing: 8,
          ),
          itemCount: 6,
          itemBuilder: (context, index) {
            final productId = 'product_$index';

            return ProductCard(
              product: Product(
                id: productId,
                name: '商品名称 $index',
                description: '商品描述',
                price: 999,
                // 添加默认图片URL
                images: [
                  'https://ts2.tc.mm.bing.net/th/id/OIP-C.MtG5BHWcXTADVW7trlPvpAHaEJ?cb=thfvnext&rs=1&pid=ImgDetMain&o=7&rm=3',
                ],
                categoryId: '1',
                stock: 100,
                rating: 4.5,
              ),
              onTap: () {
                AppRouter.push(
                  context,
                  RouterPath.productDetail,
                  arguments: productId,
                );
              },
            );
          },
        ),
      ],
    );
  }
}
